import json
import pandas as pd
from django.http import JsonResponse
from rest_framework.decorators import api_view

from .models import PriceCount,RecommendStoreNew,RecommendStorePrice,PopularStore


# 柱状图
@api_view(['POST'])
def data_bar(request):
    # param = request.data
    # category = param.get('category')
    category = "口红"
    print(category)
    # 读取数据库中的数据
    price_counts = PopularStore.objects.all().values('Shop', 'HotSum', 'category')

    # 将数据转换为 Pandas DataFrame
    df = pd.DataFrame(price_counts)
    df_category = df.loc[df['category'] == category]
    df_category = df_category[:10]

    data = {
        "Shop": df_category['Shop'].tolist(),
        "HotSum": df_category['HotSum'].tolist()
    }

    # 将数据以 JSON 格式返回
    return JsonResponse(data, safe=False)


@api_view(['POST'])
def data_line(request):
    param = request.data
    category = param.get('category')
    # category = "口红"
    print(category)
    # 读取数据库中的数据
    price_counts = RecommendStorePrice.objects.all().values('Shop', 'StorePrice', 'category')

    # 将数据转换为 Pandas DataFrame
    df = pd.DataFrame(price_counts)
    df_category = df.loc[df['category'] == category]

    df_category = df_category[:10]
    data = {
        "Shop": df_category['Shop'].tolist(),
        "StorePrice": df_category['StorePrice'].tolist()
    }

    # 将数据以 JSON 格式返回
    return JsonResponse(data, safe=False)

# 饼图
@api_view(['POST'])
def data_pie(request):

    category = "口红"
    # print(category)
    # 读取数据库中的数据
    price_counts = PriceCount.objects.all().values('PriceBox', 'Hot', 'category')

    # 将数据转换为 Pandas DataFrame
    df = pd.DataFrame(price_counts)
    df_category = df.loc[df['category'] == category]

    # 将数据格式转换为饼图所需的格式： [{"value": Hot, "name": PriceBox}, ...]
    df_category = df_category[['PriceBox', 'Hot']].rename(columns={'Hot': 'value', 'PriceBox': 'name'})

    # 将 DataFrame 转换为 JSON 格式
    data_json = df_category.to_json(orient='records', force_ascii=False)

    # 将 JSON 返回给客户端
    return JsonResponse(json.loads(data_json), safe=False)




@api_view(['POST'])
def data_hot_store(request):
    param = request.data
    category = param.get('category')
    # category = "口红"
    print(category)
    # 读取数据库中的数据
    recommendstorenew = RecommendStoreNew.objects.all().values('Title','Link','ImageLink','category','Shop')

    # 将数据转换为 Pandas DataFrame
    df = pd.DataFrame(recommendstorenew)
    df_category = df.loc[df['category'] == category]

    # 将 DataFrame 转换为 JSON 格式
    data_json = df_category.to_json(orient='records', force_ascii=False)

    print(data_json)
    # 将 JSON 返回给客户端
    return JsonResponse(json.loads(data_json), safe=False)